<?php

namespace App\Http\Common\nacos\service;

use App\Http\Common\curl\CurlUtil;
use App\Http\Common\nacos\entity\NamespaceServiceEntity;
use App\Http\Common\nacos\NacosConfig;
use Illuminate\Support\Facades\Log;

class NamespaceService extends NacosConfig
{

    const TYPE = __CLASS__;

    protected $path = '/nacos/v1/console/namespaces';

    public function __construct()
    {
        parent::__construct();
    }

    public function get(): string
    {
        try {
            $response = CurlUtil::xget($this->url);
            if ($response) {
                $response = json_decode($response, true)['data'] ?? [];
            }
            $namespace = array_column($response, null, 'namespaceShowName');
            if (!isset($namespace[$this->tenant])) {
                return '';
            }
            return $this->tenant;
        } catch (\Exception $exception) {
            Log::warning('NamespaceService get error:' . $exception->getMessage());
        }
    }

    public function set(NamespaceServiceEntity $entity): bool
    {
        $params = [
            'customNamespaceId' => $entity->customNamespaceId,
            'namespaceName' => $entity->namespaceName,
            'namespaceDesc' => $entity->namespaceDesc,
        ];

        $params = http_build_query($params);
        try {
            $resp = CurlUtil::xpost($this->url, $params);
            if ($resp) {
                return true;
            }
        } catch (\Exception $exception) {
            Log::warning('NamespaceService set error:' . $exception->getMessage());
            return false;
        }
        return true;
    }
}
